package com.xique.door.command.impl;

import com.alibaba.fastjson.JSONObject;
import com.xique.common.core.utils.StringUtils;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.door.bean.domain.AccessDevice;
import com.xique.door.bean.domain.User;
import com.xique.door.bean.domain.Visitor;
import com.xique.door.bean.domain.VisitorDevice;
import com.xique.door.bean.dto.UserDeviceHouseCodeDTO;
import com.xique.door.command.IDeviceVisitorCommandService;
import com.xique.door.constant.AccessCommandConstant;
import com.xique.door.device.command.AccessCommandHQService;
import com.xique.door.device.freeview.service.biz.FreeviewCommandBizService;
import com.xique.door.device.hq.bean.dto.HQResultDTO;
import com.xique.door.device.hq.bean.dto.HQResultDataDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author shd
 * @create 2022/3/30 18:28
 */
@Service
public class DeviceVisitorCommandServiceImpl implements IDeviceVisitorCommandService {

    @Autowired
    private AccessCommandHQService accessCommandHQService;

    @Autowired
    private FreeviewCommandBizService freeviewCommandBizService;


    @Override
    public AjaxResult downDevicesVisitors(List<AccessDevice> accessDevices, List<Visitor> visitors) {
        List<AccessDevice> hqAccessDevices = accessDevices.stream().filter(e -> e.getModel().equals(AccessCommandConstant.DeviceType.HQ)).collect(Collectors.toList());
        List<AccessDevice> freeviewAccessDevices = accessDevices.stream().filter(e -> Arrays.asList(AccessCommandConstant.DeviceType.FREEVIEW_32, AccessCommandConstant.DeviceType.FREEVIEW_45).contains(e.getModel())).collect(Collectors.toList());

        if (!hqAccessDevices.isEmpty()) {
            Object o = accessCommandHQService.downBatchVisitorInfos(hqAccessDevices, visitors);
            AjaxResult result = this.getReturnHQ(JSONObject.parseObject(o.toString(), HQResultDTO.class), "admin");
            if (AjaxResult.isError(result)) {
                return result;
            }
        }
        if (!freeviewAccessDevices.isEmpty()) {
            Object o = freeviewCommandBizService.downVisitorInfos(freeviewAccessDevices, visitors);
            AjaxResult result = this.getReturnHQ(JSONObject.parseObject(o.toString(), HQResultDTO.class), "admin");
            if (AjaxResult.isError(result)) {
                return result;
            }
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult deleteDevicesVisitors(List<AccessDevice> accessDevices, List<Visitor> visitors) {
        List<String> hqDevSns = accessDevices.stream()
                .filter(e -> e.getModel().equals(AccessCommandConstant.DeviceType.HQ))
                .map(AccessDevice::getDevSn)
                .collect(Collectors.toList());

        List<String> freeviewDevSns = accessDevices.stream()
                .filter(e -> Arrays.asList(AccessCommandConstant.DeviceType.FREEVIEW_32, AccessCommandConstant.DeviceType.FREEVIEW_45).contains(e.getModel()))
                .map(AccessDevice::getDevSn)
                .collect(Collectors.toList());

        if (!hqDevSns.isEmpty()) {
            Map<String, List<String>> customIdsMap = new HashMap<>(1);
            customIdsMap.put("customId", visitors.stream().map(Visitor::getCustomId).collect(Collectors.toList()));
            Object o = accessCommandHQService.delBatchVisitorInfos(hqDevSns, customIdsMap, AccessCommandConstant.VERSION);
            AjaxResult result = this.getReturnHQ(JSONObject.parseObject(o.toString(), HQResultDTO.class), "admin");
            if (AjaxResult.isError(result)) {
                return result;
            }
        }

        if (!freeviewDevSns.isEmpty()) {
            Object o = freeviewCommandBizService.deleteVisitorInfos(freeviewDevSns, visitors);
            AjaxResult result = this.getReturnHQ(JSONObject.parseObject(o.toString(), HQResultDTO.class), "admin");
            if (AjaxResult.isError(result)) {
                return result;
            }
        }
        return AjaxResult.success();
    }

    private AjaxResult getReturnHQ(HQResultDTO dto, String fromType) {
        if (0 != dto.getResult_code()) {
            return AjaxResult.error("下发失败");
        }
        List<String> successMsgList = new ArrayList<>();
        List<String> errorMsgList = new ArrayList<>();

        if (null != dto && null != dto.getData()) {
            for (HQResultDataDTO data : dto.getData()) {
                String message = "";
                if (!data.getStatus().equals(AccessCommandConstant.DeviceStatus.SUCCESS)) {
                    message = data.getDeviceCode() + ":" + data.getMsg() + (data.getResult() != null ? " 具体原因：" + data.getResult().getInfo().getDetail() : "") + "<br/>";
                    errorMsgList.add(message);
                } else {
                    message = data.getDeviceCode() + ":" + data.getMsg() + "<br/>";
                    successMsgList.add(message);
                }
            }
        }
        //TODO
        if (null != dto && null != dto.getData_obj()) {

        }
        String successMsg = StringUtils.join(successMsgList, "");
        String errorMsg = StringUtils.join(errorMsgList, "");
        StringBuilder returnMsg = new StringBuilder();
        if (StringUtils.isNotEmpty(errorMsg)) {
            returnMsg.append("失败下发设备如下：<br/>" + errorMsg + "<br/>");
        }
        if (StringUtils.isNotEmpty(successMsg)) {
            returnMsg.append("成功下发设备如下：<br/>" + successMsg);
        }
//        String returnMsg = "失败下发设备如下：<br/>" + errorMsg +  "<br/>成功下发设备如下：<br/>" + successMsg;
        if (AccessCommandConstant.FromType.APP.equals(fromType)) {
            StringUtils.replace(returnMsg.toString(), "<br/>", "\n");
        }
        if (!errorMsgList.isEmpty()) {
            return AjaxResult.success(returnMsg.toString());
        }
        return AjaxResult.success(returnMsg.toString());
    }
}
